#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

#include "lib.h"
#include "patch.h"
#include "patchsrv.h"
#include "log.h"
#include "logger.h"
#include "casbase.h"
#include "stdolog.h"

#define LISTEN_PORT	2052

static PatchServer* serv = (PatchServer*)0;

static BOOL __stdcall ctrlHandler(DWORD);

void
SetCurrentDirectory()
{
	TCHAR exePath[MAX_PATH + 1];
	int templen;

	templen = (int)GetModuleFileName(NULL, exePath, MAX_PATH);

	while (templen && exePath[templen - 1] != '\\')
		templen--;

	if (templen > 2)
		exePath[templen] = '\0';

	::SetCurrentDirectory((LPTSTR)exePath);
	DEBUGMSG(("%S", exePath));
}

int
main(int argc, char* argv[])
{
	int port = LISTEN_PORT;

	SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
	SetCurrentDirectory();

	if (argc == 2)
		port = atoi(argv[1]);
		
	SetConsoleCtrlHandler(ctrlHandler, TRUE);

	CasinoBase::load();
	port += CasinoBase::baseport;

	if (CasinoBase::baseport)
		printf("\n*** port adjusted by %d:  listening on %d\n",
			CasinoBase::baseport, port);
	else
		printf("\n*** listening on %d\n", port);

	Log::init(new StdoutLogger());
	serv = new PatchServer(port);
	if (serv)
		serv->run();
	delete serv;
	Log::uninit();

	return 0;
}

BOOL __stdcall ctrlHandler(DWORD event)
{
	static BOOL shuttingDown = FALSE;

	if (!shuttingDown)
	{
		shuttingDown = TRUE;

		if (serv)
			serv->stop();
	}
	return TRUE;
}
